package com.yeziji.devops.sql;

import com.yeziji.common.CommonResult;
import com.yeziji.devops.sql.constructor.PageSqlConstructor;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;

import java.util.Collection;
import java.util.List;

/**
 * @author hwy
 * @since 2024/08/01 20:24
 **/
@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class SqlPageResult extends CommonResult<Object> {
    /**
     * 当前页码, 从 0 开始
     */
    private long pageNumber;

    /**
     * 每页的数量
     */
    private long pageSize;

    /**
     * 数据总数量
     */
    private long total;

    /**
     * 总页数
     */
    private long totalPage;

    /**
     * 根据 pageSql 构造器构建分页结果集
     *
     * @param constructor 构造器
     * @param data        数据结果
     * @param total       数据总量
     * @return {@link SqlPageResult}
     */
    public static SqlPageResult buildByPageSqlConstructor(PageSqlConstructor constructor, SqlResult data, int total) {
        int totalPage = 0;
        int constructorLimit = constructor.getLimit();
        if (total < constructorLimit) {
            Object result = data.getResult();
            if (result instanceof Collection) {
                totalPage = ((List) result).size();
            }
        } else {
            totalPage = (int) Math.ceil((double) constructorLimit / total);
        }
        return SqlPageResult.builder()
                .pageNumber(constructor.getPage())
                .pageSize(constructorLimit)
                .total(total)
                .totalPage(totalPage)
                .data(data)
                .build();
    }
}
